package com.bdqn.ch10.service.impl;

import com.bdqn.ch07.pojo.SysRole;
import com.bdqn.ch07.pojo.SysUser;
import com.bdqn.ch07.service.SysUserService;
import com.bdqn.ch09.pojo.SysUser;
import com.bdqn.ch09.repository.UserRepository;
import com.bdqn.ch09.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class SysUserServiceImpl implements SysUserService {

    @Resource
    private UserRepository repository;

    @Override
    public SysUser login(String usrName, String usrPassword) {
        return null;
    }

    @Override
    public void saveUser(SysUser user) {

    }

    @Override
    public void deleteUser(Long usrId) {

    }

    @Override
    public SysUser getUser(Long usrId) {
        return null;
    }

    @Override
    public Page<SysUser> findUsers(String usrName, Long roleId, Pageable pageable) {
        Specification<SysUser> specification = new Specification<SysUser>(){
            @Override
            public jakarta.persistence.criteria.Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate>predicates = new ArrayList<>();
                if (usrName != null && !usrName.equals("")){
                    predicates.add((Predicate) criteriaBuilder.like(root.get("usrName"),"%"+usrName+"%"));
                }
                if (roleId != null && roleId.longValue()!=01){
                    SysRole role = new SysRole();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"), role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return userRepository.findAll(specification,pageable);
    }

    @Override
    public SysUser getUserByUserName(String usrName) {
        return repository.findUserByUsrName(usrName);
    }


}
